from django.shortcuts import render, redirect, HttpResponse
from app01 import models
from app01.utils.pagination import Pagination
from openpyxl import load_workbook
import openpyxl


def depart_list(request):
    """部门列表"""
    # 获取数据库中所有的部门列表
    queryset = models.Department.objects.all()
    page_obj = Pagination(request, queryset, page_size=5)
    context = {
        'queryset': page_obj.page_queryset,
        'page_str': page_obj.html()
    }
    return render(request, 'depart_list.html', context)


def depart_add(request):
    """添加部门"""
    if request.method == "GET":
        return render(request, 'depart_add.html')
    # 获取用户数据
    title = request.POST.get('title')
    # 保存到数据库
    models.Department.objects.create(title=title)
    # 重定向回列表页面
    return redirect("/depart/list/")


def depart_delete(request, nid):
    """删除部门"""
    # 删除
    models.Department.objects.filter(id=nid).delete()
    # 跳转
    return redirect('/depart/list/')


def depart_edit(request, nid):
    """修改部门"""
    if request.method == "GET":
        # 根据nid就可以获取其数据
        row_obj = models.Department.objects.filter(id=nid).first()
        return render(request, 'depart_edit.html', {'row_obj': row_obj})
    title = request.POST.get('title')
    models.Department.objects.filter(id=nid).update(title=title)
    return redirect('/depart/list/')


def depart_multi(request):
    """批量上传 (Excel)"""
    # 1. 获取用户上传的文件对象
    file_obj = request.FILES.get('exc')
    print(type(file_obj))
    # 2. 由openpyxl打开Excel文件, 并读取内容
    wb = load_workbook(file_obj)

    sheet = wb.worksheets[0]
    # 3. 循环获取每一行数据
    for row in sheet.iter_rows(min_row=2):
        text = row[0].value
        exist = models.Department.objects.filter(title=text)
        if not exist:
            models.Department.objects.create(title=text)
    return redirect('/depart/list/')
